<template>
    <div class="crud-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="反馈账号" class="el-formitem">
                    <el-input v-model="searchForm.errorName" placeholder="请输入反馈人的账号" clearable />
                </el-form-item>
                <el-form-item label="反馈手机" class="el-formitem">
                    <el-input v-model="searchForm.errorPhone" placeholder="请输入反馈人的手机号" clearable />
                </el-form-item>
                <el-form-item label="反馈类型">
                    <el-select v-model="searchForm.errorRole" placeholder="请选择状态" clearable>
                        <el-option label="未处理" value="未处理" />
                        <el-option label="已处理" value="已处理" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>搜索
                    </el-button>
                    <el-button @click="resetSearch">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="operation-area">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
                <el-icon>
                    <Delete />
                </el-icon>批量删除
            </el-button>
        </div>

        <!-- 表格区域 -->
        <div class="table-area">
            <el-table v-loading="loading" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" row-key="errorId">
                <el-table-column type="selection" width="55" :selectable="(row) => row.errorStatus !== 0" />
                <el-table-column prop="errorId" label="编号" width="55" />
                <el-table-column prop="errorName" label="反馈人账号" width="150" />
                <el-table-column prop="errorPhone" label="反馈人手机号" width="150" />
                <el-table-column prop="errorRole" label="反馈人身份" width="150" />
                <el-table-column prop="errorOrder" label="反馈的订单" width="180" />
                <el-table-column prop="errorProblem" label="反馈问题" width="180" />
                <el-table-column prop="errorCreateTime" label="反馈时间" width="180" />
                <el-table-column prop="errorStatus" label="是否解决" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.errorStatus === 1 ? 'success' : 'danger'">
                            {{ row.errorStatus === 1 ? '已解决' : '未解决' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="errorResult" label="处理结果" width="180" />
                <el-table-column prop="errorSolvingTime" label="解决时间" width="180"></el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)" :disabled="row.errorStatus === 1">
                            <el-icon>
                                <Edit />
                            </el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)" :disabled="row.errorStatus === 0">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-area">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[2, 3, 4, 5]"
                :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 新增表单 -->
        <el-dialog v-model="showAddDialog" :title="title" width="400px" :destroy-on-close="true">
            <el-form label-width="100px" :model="addForm" ref="formRef" :rules="rules">
                <el-form-item label="反馈人账号" prop="errorName">
                    <el-input v-model="addForm.errorName" placeholder="请输入反馈人账号" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="反馈人手机" prop="errorPhone">
                    <el-input v-model="addForm.errorPhone" placeholder="请输入反馈人手机号" />
                </el-form-item>
                <el-form-item label="反馈人身份" prop="errorRole">
                    <el-select v-model="addForm.errorRole" placeholder="请选择反馈人身份" clearable :disabled="isEdit">
                        <el-option label="乘客" value="乘客" />
                        <el-option label="司机" value="司机" />
                    </el-select>
                </el-form-item>
                <el-form-item label="反馈的订单" prop="errorOrder">
                    <el-input v-model="addForm.errorOrder" placeholder="请输入反馈的订单号" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="反馈的问题" prop="errorProblem">
                    <el-input v-model="addForm.errorProblem" placeholder="请输入要反馈的问题" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="反馈状态" prop="errorStatus">
                    <el-select v-model="addForm.errorStatus" placeholder="请选择状态">
                        <el-option label="未处理" :value="0" />
                        <el-option label="已处理" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="处理结果" prop="errorResult">
                    <el-input v-model="addForm.errorResult" placeholder="请输入处理结果" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>
    </div>

</template>

<script setup>
import { ref } from 'vue'; // 确保导入 ref
import request from '@/utils/request';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { Fold, Expand, ArrowDown, Search, Refresh, Plus, Delete, Edit, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, messageConfig } from 'element-plus';

const loading = ref(false)//表格是否有数据
const tableData = ref([])//表格数据
const selectedRows = ref([])//选择框选中数据
const currentPage = ref(1)//当前页
const pageSize = ref(2)//每页可有的条数
const total = ref(0)
const showAddDialog = ref(false)//新增页面
const title = ref("新增反馈");//页面的标题
const isEdit = ref(false); // 是否为编辑模式
const originalForm = ref({}); // 存储原始表单数据，用于比较
const formRef = ref(null); // 表单引用

// 搜索表单数据
const searchForm = ref({
    errorName: '',
    errorPhone: '',
    errorRole: '',
    page: 1,
    pageSize: 2
});
//添加修改按钮
const addForm = ref({
    errorName: '',
    errorPhone: '',
    errorRole: '',
    errorOrder: '',
    errorProblem: '',
    errorStatus: '',
    errorResult: ''

});
// 规则
const rules = {
    errorName: [
        { required: true, message: '请输入反馈人账号', trigger: 'blur' },
        { pattern: /^[a-zA-Z][a-zA-Z0-9]{5,9}$/, message: '账号必须由字母和数字组成，首位为字母，6-10位', trigger: 'blur' }
    ],
    errorPhone: [
        { required: true, message: '请输入反馈人的手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
    ],
    errorRole: [
        { required: true, message: '请选择反馈人身份', trigger: 'change' }
    ],
    errorOrder: [
        { required: true, message: '请输入反馈的订单号', trigger: 'change' }
    ],
    errorProblem: [
        { required: true, message: '请输入反馈问题', trigger: 'change' }
    ],
    errorStatus: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
}
//搜索按钮
const handleSearch = () => {
    getErrorList();
};
//重置按钮
const resetSearch = () => {
    searchForm.value = {
        errorName: '',
        errorPhone: '',
        errorRole: '',
        page: 1,
        pageSize: 2
    }
    getErrorList();
};
//重置添加表单数据
const resetAddFrom = () => {
    addForm.value = {
        errorName: '',
        errorPhone: '',
        errorRole: '',
        errorOrder: '',
        errorProblem: '',
        errorStatus: '',
        errorResult: ''
    }
}
//查询反馈的问题列表
const getErrorList = () => {
    console.log()
    request.get('/error/page', searchForm.value // 直接传递 searchForm.value 作为 params
    ).then((res) => {
        console.log(res);
        tableData.value = res.data.errorList.list;
        total.value = res.data.count;
    }).catch((err) => {
        console.error('获取失败：', err)
    })
}
//页面初始查询数据
getErrorList();

// 分页大小改变
const handleSizeChange = (val) => {
    pageSize.value = val;
    getErrorList();
}
// 页码改变
const handleCurrentChange = (val) => {
    currentPage.value = val;
    getErrorList();
}
//选择框选中的值
const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
    console.log('Selected rows:', rows);
}

//批量删除按钮
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据');
        return;
    }

    // 检查是否有errorStatus为0的行被选中
    const hasUnprocessedRows = selectedRows.value.some(row => row.errorStatus === 0);
    if (hasUnprocessedRows) {
        ElMessage.warning('未处理的反馈不能删除');
        return;
    }

    ElMessageBox.confirm(
        `确认删除选中的 ${selectedRows.value.length} 条数据吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 获取所有选中行的ID
            const ids = selectedRows.value.map(item => item.errorId);
            console.log(ids);

            // 调用批量删除
            request.delete(`/error/deleteBatch?errorIds=${ids}`)
                .then(() => {
                    ElMessage.success('批量删除成功');
                    getErrorList(); // 刷新数据
                })
                .catch(err => {
                    console.error('批量删除失败:', err);
                    ElMessage.error('批量删除失败');
                });
        })
        .catch(() => {
            // 用户取消删除
            ElMessage.info('已取消删除');
        });
};
//表格的编辑按钮
const handleEdit = (row) => {
    console.log(row);
    title.value = "修改反馈";
    isEdit.value = true;

    // 存储原始数据用于后续比较
    originalForm.value = JSON.parse(JSON.stringify(row));

    // 回显数据到表单
    addForm.value = {
        errorName: row.errorName,
        errorPhone: row.errorPhone,
        errorRole: row.errorRole,
        errorOrder: row.errorOrder,
        errorProblem: row.errorProblem,
        errorStatus: row.errorStatus,
        errorResult: row.errorResult,
        errorId: row.errorId // 保存ID用于提交
    };

    showAddDialog.value = true;
}
//表格里的删除按钮
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确认删除该条数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 调用删除API
            console.log(row.errorId);
            request.delete(`/error/deleteById?errorId=${row.errorId}`)
                .then(() => {
                    ElMessage.success('删除成功');
                    getErrorList(); // 刷新数据
                })
                .catch(err => {
                    console.error('删除失败:', err);
                    ElMessage.error('因网络波动，删除失败');
                });
        })
        .catch(() => {
            // 用户取消删除
            ElMessage.info('已取消删除');
        });
}
//新增按钮
const handleAdd = () => {
    resetAddFrom();
    title.value = "新增反馈";
    isEdit.value = false;
    showAddDialog.value = true;
};
//新增、编辑页面的确定按钮
const submitAddForm = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            return false;
        }

        // 检查处理结果和状态的一致性
        if (addForm.value.errorResult && addForm.value.errorResult.trim() !== '' && addForm.value.errorStatus !== 1) {
            ElMessageBox.confirm(
                '您已填写处理结果，是否将处理状态修改为已处理？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                addForm.value.errorStatus = 1; // 将状态改为已处理
                submitForm(); // 提交表单
            }).catch(() => {
                // 用户选择取消，不做任何操作
                ElMessage.info('请手动修改处理状态');
            });
            return;
        }

        submitForm(); // 如果验证都通过，直接提交表单
    });
}

// 抽取提交表单的逻辑为单独的函数
const submitForm = () => {
    if (isEdit.value) {
        // 编辑模式下验证是否至少修改了一项可编辑字段
        if (addForm.value.errorPhone === originalForm.value.errorPhone &&
            addForm.value.errorStatus === originalForm.value.errorStatus) {
            ElMessage.warning('请至少修改手机号或状态中的一项');
            return;
        }

        // 如果状态改为已处理(1)，则必须填写处理结果
        if (addForm.value.errorStatus === 1 && (!addForm.value.errorResult || addForm.value.errorResult.trim() === '')) {
            ElMessage.warning('将状态改为已处理时，必须填写处理结果');
            return;
        }

        // 这里可以添加提交到后端的逻辑
        console.log('提交编辑表单', addForm.value);
        request.put('/error/updateError', addForm.value)
            .then((res) => {
                console.log(res);
                if (res.message == "修改成功") {
                    ElMessage.success('修改成功');
                    showAddDialog.value = false;
                    getErrorList(); // 刷新列表
                }
            })
            .catch((err) => {
                console.log(err);
                ElMessage.error('因网络波动，修改未成功，请重试');
            })

    } else {
        // 新增模式 - 检查所有字段是否填写完整
        if (!addForm.value.errorName || !addForm.value.errorPhone ||
            !addForm.value.errorRole || !addForm.value.errorOrder ||
            !addForm.value.errorProblem || addForm.value.errorStatus === '') {
            ElMessage.warning('请填写完整');
            return;
        }

        // 表单验证通过，提交表单
        console.log('提交新增表单', addForm.value);
        request.post('/error/addError', addForm.value)
            .then((res) => {
                console.log(res);
                if (res.message == "新增成功") {
                    ElMessage.success('添加成功');
                    showAddDialog.value = false;
                    getErrorList(); // 刷新列表
                    return
                }
                ElMessage.error('因网络波动，新增未成功，请重试');
            }).catch((err) => {
                console.log(err);
                ElMessage.error('因网络波动，新增未成功，请重试');
            })
    }
}
</script>

<style>
.crud-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.operation-area {
    margin-bottom: 20px;
}

.table-area {
    margin-bottom: 20px;
}

.pagination-area {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.pagination-area span {
    padding-left: 10px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.el-button [class*="el-icon"]+span {
    margin-left: 5px;
}

.search-form .el-form-item {
    min-width: 190px;
}

.el-form-item span {
    /* padding-left: 10px; */
}

.el-formitem {
    width: 225px;
}
</style>
